package com.elcl.widget.comp.edt;


import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.EditText;

import com.elcl.andbaselibrary.R;

/**
 * @author LCL
 * 2014-11-17
 * 带有清除功能的EditText
 * 描述：监听两个事件，一个：textChange来实现叉号的有无，一个：点击的区域是否在叉号的区域
 */
public class EditTextWithClear extends EditText {
	Drawable mCancle;
	private int interval = 10;//取消按钮距离EditText右边的距离
	private int drawableTouchRect = 0;//触摸的区域
	private int touchLimit = 0;// 进入清除图标触摸区域的界限

	public EditTextWithClear(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	public EditTextWithClear(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public EditTextWithClear(Context context) {
		super(context);
		init();
	}

	private Drawable[] drawables;//防止drawableleft有图片的时候
	private void init() {
		mCancle = getResources().getDrawable(R.drawable.edit_clear_normal);
		drawableTouchRect = mCancle.getIntrinsicWidth() + interval;//触摸区域的大小
		drawables = getCompoundDrawables();
		setDrawableVisible(getText());//初始化
		addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				setDrawableVisible(s);
			}

		});
	}
	
	private void setDrawableVisible(Editable s) {
		if (TextUtils.isEmpty(s)) {
			setCompoundDrawablesWithIntrinsicBounds(drawables[0], null, null, null);
		}else{
			setCompoundDrawablesWithIntrinsicBounds(drawables[0], null, mCancle, null);
		}
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		super.onTouchEvent(event);
		if (touchLimit == 0) {
			touchLimit = getWidth() - drawableTouchRect;
		}
		if (event.getAction() == MotionEvent.ACTION_UP) {
			int curX = (int) event.getX();
			if (curX > touchLimit && !TextUtils.isEmpty(getText())) {//点击的X轴坐标大于清除按钮的左边，就将其
				setText("");
			}
		}
		return true;
	}
}
